package com.e2edour.runtime.utils

import java.io.{BufferedReader, InputStreamReader, OutputStreamWriter}
import java.net.{HttpURLConnection, URL}

import com.e2edour.runtime.properties.AppContextConfig

/**
  * <p>
  *
  * @author King 
  * @since 2017/1/17
  */
object HttpUtil {
  /**
    * 向后台发送post请求
    *
    * @param url
    * @param param
    * @return
    */
  def sendPost(url: String, param: String): String = {
    var out: OutputStreamWriter = null
    var in: BufferedReader = null
    var result: String = ""
    try {
      val realUrl = new URL(url)
      val conn: HttpURLConnection = realUrl.openConnection().asInstanceOf[HttpURLConnection]
      conn.setDoOutput(true)
      conn.setDoInput(true)
      conn.setUseCaches(false)
      conn.setRequestMethod("POST")
      conn.setConnectTimeout(Integer.parseInt(AppContextConfig.get("connect.timeout", "5000")))
      conn.setReadTimeout(Integer.parseInt(AppContextConfig.get("read.timeout", "5000")))
      conn.setRequestProperty("Content-Type", "application/json")
      conn.setRequestProperty("Accept", "application/json")
      conn.setRequestProperty("Authorization", "token")
      conn.setRequestProperty("tag", "htc_new")
      conn.connect();
      out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8")
      out.write(param)
      out.flush()
      out.close()
      in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))
      result = in.readLine()
    } catch {
      case e: Exception =>
        e.printStackTrace
        out.close
        in.close()
    }
    result
  }
}
